package com.bingguo.config;

import com.bingguo.util.BaseUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.util.AntPathMatcher;

import javax.annotation.PostConstruct;
import java.util.List;

@Configuration
@RefreshScope
@ConfigurationProperties(prefix = UrlProperties.PREFIX)
public class UrlProperties {

    public final static String PREFIX = "gateway.urls";

    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    private final static List<String> EXCLUDES = BaseUtils.list(
            "/favicon.ico",
            "/error"
    );

    /**
     * 白名单url
     */
    private List<String> whiteUrls;

    /**
     * 黑名单url
     */
    private List<String> blackUrls;

    public List<String> getWhiteUrls() {
        return whiteUrls;
    }

    public void setWhiteUrls(List<String> whiteUrls) {
        this.whiteUrls = whiteUrls;
    }

    public List<String> getBlackUrls() {
        return blackUrls;
    }

    public void setBlackUrls(List<String> blackUrls) {
        this.blackUrls = blackUrls;
    }

    /**
     * 不拦截白名单，支持通配符
     * @param registry
     */
    public void permitAll(ServerHttpSecurity.AuthorizeExchangeSpec registry) {
        EXCLUDES.stream().forEach((url) -> registry.pathMatchers(url).permitAll());
    }

    /**
     * 不拦截白名单，支持通配符
     * @param url
     * @return
     */
    public boolean matchWhiteUrlsList(String url) {
        return EXCLUDES != null ? EXCLUDES.stream().anyMatch(blackUrl -> ANT_PATH_MATCHER.match(blackUrl, url)) : false;
    }

    /**
     * 拦截黑名单，匹配黑名单
     * @param url
     * @return
     */
    public boolean matchBlackList(String url) {
        return blackUrls != null ? blackUrls.stream().anyMatch(blackUrl -> ANT_PATH_MATCHER.match(blackUrl, url)) : false;
    }

    @PostConstruct
    public void init(){
        if(whiteUrls != null && whiteUrls.size() > 0){
            EXCLUDES.addAll(whiteUrls);
        }
    }

}
